package com.lhy.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String url, Model model,
                        @CookieValue(value = "sso_token",required = false) String cookie) {
        if(!StringUtils.isEmpty(cookie)){
            return "redirect:" + url + "?token=" + cookie;
        }
        // 登录成功，跳回到
        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/dologin")
    public String dologin(String url, String name, String password, HttpServletResponse resp) {

        // 登录成功，跳回到
        if(!StringUtils.isEmpty(name) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            Cookie sso_token = new Cookie("sso_token", uuid);
            resp.addCookie(sso_token);
            redisTemplate.opsForValue().set(uuid, name);
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登录失败，跳到登录页面
        return "login";
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token")String token){
        return redisTemplate.opsForValue().get(token);
    }


}
